﻿using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using SER = CPPEI.ETL.Domain.Services;
using ENT = CPPEI.ETL.Domain.Entities;
using MOD = CPPEI.ETL.Domain.Models;

namespace CPPEI.ETL.WebApi
{
    [CPPEI.WebApi.AuthGetAction("ETL", "GetDataServiceFolderTree", "1.0")]
    public class GetDataServiceFolderTreeAction : BaseAction<GetDataServiceFolderTreeParams, GetDataServiceFolderTreeResult>
    {
        protected override ActionResult<GetDataServiceFolderTreeResult> OnExecute(ActionContext context,
            SysParameters sysParameters,
            GetDataServiceFolderTreeParams opParams)
        {
            GetDataServiceFolderTreeResult result = new GetDataServiceFolderTreeResult();

            SER.DtSerService ser = new SER.DtSerService();

            List<MOD.MDtSerFolder> roots = ser.GetFolderTree(opParams.ParentId);

            foreach (var root in roots)
            {
                result.Items.Add(Convert(root));
            }

            return new ActionResult<GetDataServiceFolderTreeResult>(result);
        }

        private GetDataServiceFolderTreeResult.Item Convert(MOD.MDtSerFolder folder)
        {
            GetDataServiceFolderTreeResult.Item item = new GetDataServiceFolderTreeResult.Item();
            item.Id = folder.Id;
            item.Caption = folder.Caption;
            item.Code = folder.Code;

            foreach (var child in folder.Children)
            {
                item.Items.Add(Convert(child));
            }
            return item;
        }
    }

    public class GetDataServiceFolderTreeParams
    {
        [Parameter]
        public Guid ParentId { get; set; }
    }

    public class GetDataServiceFolderTreeResult
    {
        public List<Item> Items { get; set; }
        public GetDataServiceFolderTreeResult()
        {
            Items = new List<Item>();
        }

        public class Item
        {
            public Guid Id { get; set; }

            public string Code { get; set; }

            public string Caption { get; set; }

            public List<Item> Items { get; set; }

            public Item()
            {
                Items = new List<Item>();
            }
        }
    }
}
